package com.xiaoyuzhou.logic;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import android.content.Context;
import com.xiaoyuzhou.untity.AddressData;
import com.xiaoyuzhou.untity.Weather;
import com.xiaoyuzhou.untity.WeatherHeap;
import com.xiaoyuzhou.utils.NetUtils;
import com.xiaoyuzhou.utils.SPUtils;
import com.xiaoyuzhou.utils.StaticData;

public class DataService {
	
	public static final String WEATHER_DETAIL = "weather_detail";
	public static final String TEMPERATURE = "temperature";
	public static final String WIND = "wind";
	public static final String UPDATE_TIME = "update_time";
	public static final String LOCATION = "location";
	public static final String CHECKLASTUPDATE = "checklastupdate";
	
	public static final String XML_SUFFIX = ".xml";
	
	public static final String SP_NAME_SUPPORTCITY = "supportcity";
	public static final String SP_NAME_LASTUPDATE = "lastupdate";
	
	public static final String HOST = "http://webservice.webxml.com.cn";
	
	public static final String THE_USER_ID = "&theUserID=";
	
	public static final Map<String, String> province = new HashMap<String, String>();
	
	public static Map<String, String> getSupportCity(String regionCode) {
		if(regionCode == null || regionCode.equals("")) {
			return null;
		}
		//http://webservice.webxml.com.cn/WebServices/WeatherWS.asmx/getSupportCityDataset?theRegionCode=311101
		final String url = HOST + "/WebServices/WeatherWS.asmx/getSupportCityDataset?theRegionCode=" + regionCode;
		Map<String, String> cities = new HashMap<String, String>();
		InputStream is = NetUtils.getInputStream(url);
		try {
			cities = XmlParser.parseCityDateSet(is);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return cities;
	}
	
	/**
	 * 遍历保存得到的城市编码信息
	 * Description:
	 * @param context
	 * @param cities
	 * @return 是否保存成功
	 */
	public static boolean saveSupportCity(Context context, Map<String, String> cities) {
		if(cities != null) {
			Iterator<Entry<String, String>> iter = cities.entrySet().iterator();
			while (iter.hasNext()) {
				Entry<String, String> entry = (Entry<String, String>) iter.next();
				String key = entry.getKey();
				String value = entry.getValue();
				SPUtils.saveData(context, DataService.SP_NAME_SUPPORTCITY, key, value);
			}
			return true;
		}
		return false;
	}
	
	/**
	 * 以标准xml保存天气数据，保存至项目目录下file目录，文件名为城市名
	 * Description:
	 * @param weatherHeap
	 * @return
	 * @throws Exception
	 */
	public static void saveForecast2Data(Context context, WeatherHeap weatherHeap) {
		try {
			String path = weatherHeap.getLocation() + XML_SUFFIX;
			FileOutputStream fos = context.openFileOutput(path, Context.MODE_PRIVATE);
			XmlParser.serializeWeather(weatherHeap, fos);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 从数据库文件中取天气数据
	 * @param location	哪一个城市
	 * @param date	哪一天的天气
	 * @return
	 */
	public static Weather getWeatherFromData(Context context, String location, String date) {
		try {
			String path = location + XML_SUFFIX;
			FileInputStream fis = context.openFileInput(path);
			Weather weather = XmlParser.parseWeather(fis, date);
			System.out.println(weather.toString());
			return weather;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 从SP中取城市编码，优先查找城区，若城区无对应结果，再查找城市
	 * @param district
	 * @param city
	 * @return
	 */
	public static String getCityCodeFromSP(Context context, String district, String city) {
		//先根据城区寻找
		String cityCode = SPUtils.readData(context, DataService.SP_NAME_SUPPORTCITY, district);
		//如果没有数据，再根据城市寻找
		if(cityCode == null || cityCode.equals("")) {
			cityCode = SPUtils.readData(context, DataService.SP_NAME_SUPPORTCITY, city);
			if(cityCode == null || cityCode.equals("")) {
				return null;
			}
		}
		return cityCode;
	}
	
	/**
	 * 获取定位城市
	 * Description:
	 * @param lat2
	 * @param lng2
	 * @return
	 *<br/> ModifiedLog:
	 *<br/> Log ID: 1.0 (Log编号 依次递增)
	 * <br/>Modified By: liubin Email:liubin@d-heaven.com at 2012-10-18 下午02:08:18
	 */
	public static AddressData getAddressByLocate(double lat2, double lng2) {
		//http://api.map.baidu.com/geocoder?output=xml&location=39.9623586,116.3353019&key=37492c0ee6f924cb5e934fa08c6b1676
		final String URL = "http://api.map.baidu.com/geocoder?output=xml&location=";
		final String key = "&key=37492c0ee6f924cb5e934fa08c6b1676";
		String requestData = URL + lat2 + "," + lng2 + key;
		InputStream is = NetUtils.getInputStream(requestData);
		AddressData address = null;
		if(is != null) {
			try {
				address = XmlParser.parseAddressData(is);
				System.out.println(address.toString());
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return address;
	}
	
	public static WeatherHeap getWeather(String cityCode) {
		if(cityCode == null || cityCode.equals("")) {
			return null;
		}
		//http://webservice.webxml.com.cn/WebServices/WeatherWS.asmx/getWeather?theCityCode=12&theUserID=
		final String url = HOST + "/WebServices/WeatherWS.asmx/getWeather?theCityCode=" + cityCode + THE_USER_ID;
		InputStream is = NetUtils.getInputStream(url);
		WeatherHeap w = null;
		try {
			w = XmlParser.parseWeatherHeap(is, cityCode);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return w;
	}
	
	public static Map<String, String> getProvince() {
		//http://webservice.webxml.com.cn/WebServices/WeatherWS.asmx/getRegionProvince?
		final String url = HOST + "/webservice.webxml.com.cn/WebServices/WeatherWS.asmx/getRegionProvince?";
		Map<String, String> provinces = new HashMap<String, String>();
		InputStream is = NetUtils.getInputStream(url);
		try {
			provinces = XmlParser.parseProvince(is);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return provinces;
	}
	
	/**
	 * 首先判断定位城市是否变化，再根据当前时间与上次刷新时间之差（如果有），判断是否需要刷新widget
	 * @param context
	 * @param location
	 * @return
	 */
	public static boolean should_updateWeather(Context context, String location) {
		long last_update_time = 0;
		String last_location = SPUtils.readData(context, DataService.SP_NAME_LASTUPDATE, DataService.LOCATION);
		//定位城市有变化，立即请求新数据
		if(!last_location.equals(location)) {
			return true;
		}
		try {
			last_update_time = Long.valueOf(SPUtils.readData(context, DataService.SP_NAME_LASTUPDATE, DataService.UPDATE_TIME));
			System.out.println("last_update_time:" + last_update_time);
		} catch (NumberFormatException e) {
			return true;
		}
		long now = System.currentTimeMillis();
		System.out.println("now:" + now);
		if((now - last_update_time) >= StaticData.update_time) {
			return true;
		}
		return false;
	}
	
	
	static {
		province.put("黑龙江", "3113");
		province.put("吉林", "3114");
		province.put("辽宁", "3115");
		province.put("内蒙古", "3116");
		province.put("河北", "3117");
		province.put("河南", "3118");
		province.put("山东", "3119");
		province.put("山西", "311310");
		province.put("江苏", "311311");
		province.put("安徽", "311312");
		province.put("陕西", "311313");
		province.put("宁夏", "311314");
		province.put("甘肃", "311315");
		province.put("青海", "311316");
		province.put("湖北", "311317");
		province.put("湖南", "311318");
		province.put("浙江", "311319");
		province.put("江西", "311320");
		province.put("福建", "311321");
		province.put("贵州", "311322");
		province.put("四川", "311323");
		province.put("广东", "311324");
		province.put("广西", "311325");
		province.put("云南", "311326");
		province.put("海南", "311327");
		province.put("新疆", "311328");
		province.put("西藏", "311329");
		province.put("台湾", "311330");
		province.put("北京", "311101");
		province.put("上海", "311102");
		province.put("天津", "311103");
		province.put("重庆", "311104");
		province.put("香港", "311201");
		province.put("澳门", "311202");
		province.put("钓鱼岛", "311203");
	}
}
